<!-- 返回顶部组件 -->
<template>
  <div v-show="goTopShow" id="goTop">
    <!-- <div class="goHome" @click="goHome">
      <i class="goHomeIcon">
        <i class="textTop">主页</i>
      </i>
    </div> -->
    <div class="goTop" @click="goTop">
      <i class="goTopIcon">
        <i class="textTop">top</i>
      </i>
    </div>
  </div>
</template>
<script>
export default {
  name: "goTop",
  data() {
    return {
      scrollTop: "",
      goTopShow: false,
    };
  },
  methods: {
    handleScroll() {
      this.scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      if (this.scrollTop > 100) {
        this.goTopShow = true;
      } else {
        this.goTopShow = false;
      }
    },
    goTop() {
      let timer = null,
        _that = this;
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        if (_that.scrollTop > 0) {
          _that.scrollTop -= 250; //控制速度
          document.body.scrollTop = document.documentElement.scrollTop =
            _that.scrollTop;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
          _that.goTopShow = false;
        }
      });
    },
    goHome() {
      this.$router.push("/");
    },
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
};
</script>
 
<style scoped>
.goTop,
.goHome {
  position: fixed;
  right: 20px;
  bottom: 150px;
  width: 50px;
  height: 50px;
  text-align: center;
  border-radius: 100%;
  background: rgba(0, 0, 0, 0.5);
  cursor: pointer;
  /* border: 2px solid #b9b9b9 */
}
.goHome {
  bottom: 201px;
}
.goTop:hover {
  background: rgba(0, 0, 0, 0.85);
}
.goHome:hover {
  background: rgba(0, 0, 0, 0.85);
}
.goTopIcon,
.goHomeIcon {
  display: block;
  width: 40px;
  height: 50px;
  background: url("./../assets/image/top1.png");
  background-size: 55%;
  background-repeat: no-repeat;
  background-position: 80% 28%;
}
.goHomeIcon {
  background: url("./../assets/image/home.png");
  background-size: 60%;
  background-repeat: no-repeat;
  background-position: 80% 42%;
}

.textTop {
  color: #e8e8e8;
  position: absolute;
  bottom: 10%;
  left: 33%;
  font-size: 15px;
}
</style>
